package com.thesis.controller;

import com.thesis.common.CommonEnum;
import com.thesis.common.MD5Util;
import com.thesis.common.ResponseBean;
import com.thesis.entity.SysAdmin;
import com.thesis.service.AdminService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by Anvy at 2020/4/19.
 */
@Controller
@RequestMapping("/admin")
public class AdminController {

    private static  final Logger log= LoggerFactory.getLogger(AdminController.class);

    @Autowired
    private AdminService adminService;
    

    @Value("${com.jane.security.md5.key}")
    private String md5Key;

    @RequestMapping("/login")
    public String login(HttpSession session) {
        if (session.getAttribute("admin") != null) {
            return "redirect:/admin/index";
        }
        return "login";
    }

    @RequestMapping("/index")
    public String index() {
        return "index";
    }

    @RequestMapping("/welcome")
    public String welcome(Model model) {
        return "welcome";
    }

    @RequestMapping("/notFound")
    public String notFound() {
        return "admin/404";
    }

    @RequestMapping("/error")
    public String error() {
        return "admin/500";
    }

    @RequestMapping("addPage")
    public String addAdminPage(HttpServletRequest request,Model model){
        Object object=  request.getSession().getAttribute("admin");
        if(object==null){
            model.addAttribute("msg","当前操作用户非管理员，不能添加管理员！");
            return "admin/500";
        }
        return "admin/add";
    }

    @RequestMapping("add")
    @ResponseBody
    public ResponseBean add(SysAdmin sysAdmin){
        log.debug("添加的管理员对象："+sysAdmin);
        if(sysAdmin==null|| StringUtils.isEmpty(sysAdmin.getMobile())){
            log.debug("添加的管理员对象不合法！");
            return  new ResponseBean(false, CommonEnum.BAD_REQUEST);
        }
        String password = sysAdmin.getPassword();
        if(StringUtils.isEmpty(password)){
            log.debug("密码为空！");
            return new ResponseBean(false,CommonEnum.BAD_REQUEST);
        }
        sysAdmin.setPassword(MD5Util.md5(password,md5Key));
        int i = adminService.insertSelective(sysAdmin);
        return new ResponseBean(true,sysAdmin,CommonEnum.SUCCESS_OPTION);
    }

    /**
     * 跳转到管理员编辑界面
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("editPage")
    public String editAdminPage(HttpServletRequest request,Model model){
        Object object=  request.getSession().getAttribute("admin");
        if(object==null){
            model.addAttribute("msg","当前操作用户非管理员，不能编辑管理员！");
            return "admin/500";
        }
        return "admin/edit";
    }
    @RequestMapping("edit")
    @ResponseBody
    public ResponseBean editAdmin(SysAdmin sysAdmin,HttpServletRequest request){
        log.debug("修改的管理员对象："+sysAdmin);
        String mobile = sysAdmin.getMobile();
        if(sysAdmin==null|| StringUtils.isEmpty(mobile)){
            log.debug("修改的管理员对象不合法！");
            return  new ResponseBean(false,CommonEnum.BAD_REQUEST);
        }
        SysAdmin checkAdmin=new SysAdmin();
        checkAdmin.setMobile(mobile);
        checkAdmin.setId(sysAdmin.getId());
        List<SysAdmin> sysAdminCheck = adminService.checkObj(checkAdmin);
        if(sysAdminCheck!=null&&sysAdminCheck.size()>0){
            log.debug("手机号已经被占用！");
            return new ResponseBean(false,"手机号已经被占用！");
        }
        String password = sysAdmin.getPassword();
        if(StringUtils.isEmpty(password)){
            log.debug("密码为空！");
            return new ResponseBean(false,CommonEnum.BAD_REQUEST);
        }
        sysAdmin.setPassword(MD5Util.md5(password,md5Key));
        int i = adminService.updateByPrimaryKeySelective(sysAdmin);
        //更新session中当前管理员信息
        request.getSession().setAttribute("admin",sysAdmin);
        return new ResponseBean(true,sysAdmin,CommonEnum.SUCCESS_OPTION);
    }

    @RequestMapping("/checkLogin")
    @ResponseBody
    public ResponseBean checkLogin(SysAdmin admin, HttpSession session, @RequestParam String verifyCode) {
        //首先验证验证码是否存在
        String trueVerifyCode = (String) session.getAttribute("verifyCode");
        if (trueVerifyCode == null) {
            return new ResponseBean(false, CommonEnum.REFRESH_VERIFYCODE);
        }

//        //判断验证码是否输入正确（验证码忽略大小写）
//        if (!trueVerifyCode.equalsIgnoreCase(verifyCode)) {
//            return new ResponseBean(false, CommonEnum.ERROR_VERIFYCODE);
//        }

        //根据手机号查找用户
        SysAdmin dbAdmin = adminService.findByMobile(admin.getMobile());
        //判断是否存在当前用户
        if (dbAdmin == null) {
            return new ResponseBean(false, CommonEnum.NO_USER_EXIST);
        }
        //判断密码是否正确
        if (!MD5Util.md5Verify(admin.getPassword(), this.md5Key, dbAdmin.getPassword())) {
            return new ResponseBean(false, CommonEnum.INVALID_PASSWORD);
        }
        //通过所有验证
        session.setAttribute("admin", dbAdmin);
        session.setAttribute("type", 3);
        return new ResponseBean<>(true, "登录成功！", CommonEnum.LOGIN_SUCCESS);
    }

    @RequestMapping("/logOut")
    @ResponseBody
    public ResponseBean logOut(HttpSession session) {
        session.removeAttribute("admin");
        session.removeAttribute("user");
        return new ResponseBean(true, CommonEnum.LOGOUT_SUCCESS);
    }
}
